package com.qf.dao.daoImpl;

import com.qf.dao.ProfileDao;
import com.qf.pojo.Page;
import com.qf.pojo.Profile;
import com.qf.util.DBUtil;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.SQLException;
import java.util.List;

public class ProfileDaoImpl implements ProfileDao {
    private QueryRunner qr = new QueryRunner(DBUtil.getDateSource());

    @Override
    public List<Profile> findAll() {

        String sql = "select * from t_profile";
        try {
            return qr.query(sql, new BeanListHandler<>(Profile.class));
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
}

    @Override
    public Profile findOneById(int id) {
        String sql ="select * from t_profile where id = ?";
        try {
            return qr.query(sql,new BeanHandler<>(Profile.class),id);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return  null;
    }

    public int  update(int id, Profile profile) {
        String sql ="update t_profile set  name= ?,birthday=?,gender=?,career=?,address=?,mobile=?,picture=? where id = ?";
        try {
            return qr.update(sql,profile.getName(),profile.getBirthday(),
                    profile.getGender(),profile.getCareer(),profile.getAddress(),profile.getMobile(),profile.getPicture(),id);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }

    @Override
    public int selectAllByPageCount() {
        String sql = "select count(*) from t_profile";
        try {
            long count = qr.query(sql, new ScalarHandler<Long>());
            return (int)count;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }

    @Override
    public List<Profile> selectAllByPage(Page page) {
        String sql = "select * from t_profile limit ?,?";
        try {
            List<Profile> list = qr.query(sql, new BeanListHandler<Profile>(Profile.class), page.getStartRows(), page.getPageSize());
            return list;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }


}
